import datetime,json,multiprocessing,os,json,sys
import pandas as pd
import numpy as np
import cv2
import patoolib

class JavaHashStr(str):
	def __hash__(self):
		hashCode = 0
		for char in self:
			hashCode = (hashCode * 31 + ord(char)) & (2**32 - 1)  # unsigned
		if hashCode & 2**31:
			hashCode -= 2**32  # make it signed
		return hashCode

def get_qr_str(img_path, detec_type='opencv'):
	if detec_type == 'wechat':
		img = cv2.imread(img_path)
		qrcode = cv2.wechat_qrcode_WeChatQRCode()
		result, points = qrcode.detectAndDecode(img)
		return result[0] if result[0] else False
	else:
		img = cv2.imread(img_path)
		qrcode = cv2.QRCodeDetector()
		result, points, code = qrcode.detectAndDecode(img)
		return result if result else False

def main():
	qr_src_dir = os.path.join(os.getcwd(), sys.argv[1])
	mobile_acct = os.path.join(os.getcwd(), sys.argv[2])
	sp_acct = os.path.join(os.getcwd(), sys.argv[3])
	out_file = os.path.join(os.getcwd(), sys.argv[4])
	qr_tgt_dir = os.path.join(os.getcwd(), sys.argv[5])

	print(f"qr_src_dir: {qr_src_dir}")
	print(f"mobile_acct: {mobile_acct}")
	print(f"sp_acct: {sp_acct}")
	print(f"out_file: {out_file}")
	print(f"qr_tgt_dir: {qr_tgt_dir}")

	'''
	if not os.path.exists(qr_tgt_dir):
		os.makedirs(qr_tgt_dir)

	for qr in os.listdir(qr_src_dir):
		qr_img = os.path.join(qr_src_dir, qr)
		
		if qr_img.endswith('zip') or qr_img.endswith('rar'):
			patoolib.extract_archive(qr_img, outdir=qr_tgt_dir)
		else:
			qr_img2 = os.path.join(qr_tgt_dir, qr)
			print(f"{qr_img} is not a zip or rar file. {qr_img2}")
			cmd = f'copy "{qr_img}" "{qr_img2}"'
			print(cmd)
			os.system(cmd)
	'''

	cust_hash = {}
	org_hash = {}
	sp_hash = {}

	with open(sp_acct, encoding='utf-8') as f:
		for i in f.readlines():
			if i.isspace():
				continue
			line = i.strip('\n').split('|')
			sp_hash[str(line[0])] = '1'
	
	cnt = 0
	with open(mobile_acct, encoding='utf-8') as f:
		for i in f.readlines():
			cnt += 1
			if i.isspace():continue
			if cnt == 1:continue
			line = i.strip('\n').split('|')
			if str(line[4]) in ['a'] and str(line[0]) not in sp_hash:
				cust_hash[str(line[0])] = '1'
			elif str(line[4]) not in ['a'] and str(line[0]) not in sp_hash:
				org_hash[str(line[0])] = '1'
	
	out_handle = open(out_file, 'w', encoding='utf-8')

	cnt = 0
	for qr in os.listdir(qr_src_dir):
		qr_img = os.path.join(qr_src_dir, qr)
		if os.path.isfile(qr_img) and qr.split('.')[-1] in ['png','jpg','jpeg','gif','bmp']:
			qr_str = get_qr_str(qr_img, 'wechat')
			if qr_str:
				cnt += 1
				old_qrcode = qr_str
				raw_msisdn = str(qr.split('_')[0]) if qr.startswith('225') else str('225' + qr.split('_')[0])
				msisdn = str(raw_msisdn) if str(raw_msisdn) in cust_hash else ''
				short_code = raw_msisdn[3:] if str(raw_msisdn) in org_hash else ''

				if msisdn == '' and short_code == '':
					print(f"debug 2: {qr} img not in cust and org.")
					continue
				
				qr_mapping_id = '20' + (6 - len(str(cnt))) * '0' + str(cnt)
				old_Qr_Hash = hash(JavaHashStr(old_qrcode))
				#old_Qr_Hash = ''
				import_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

				if msisdn == '':
					sql = f"insert into owner.table_name (QR_MAPPING_ID, OLD_QRCODE, OLD_QR_HASH, SHORT_CODE, MSISDN, IMPORT_TIME) values ({int(qr_mapping_id)}, '{str(old_qrcode)}', {int(old_Qr_Hash)}, '{str(short_code)}', null, '{str(import_time)}');\n"
				elif short_code == '':
					sql = f"insert into owner.table_name (QR_MAPPING_ID, OLD_QRCODE, OLD_QR_HASH, SHORT_CODE, MSISDN, IMPORT_TIME) values ({int(qr_mapping_id)}, '{str(old_qrcode)}', {int(old_Qr_Hash)}, null, '{str(msisdn)}', '{str(import_time)}');\n"
				
				out_handle.write(sql)
			else:
				print(f"{qr} is None.")
		else:
			print(f"{qr_img} is not img file.")

	out_handle.write('commit;')
	out_handle.close()
	
if __name__ == '__main__':
	time1 = datetime.datetime.now()
	main()
	time2 = datetime.datetime.now()

	print('start time: ', time1)
	print('end time: ', time2)
	print('total time: ', (time2 - time1))